<template>
  <div></div>
</template>

<script>
  
import md from '@/markdowns/jsBase-prototype.md'

export default {
  name: 'jsBase-prototype',
  components: {
    
  },
  data () {
    return {
      
    }
  },
  watch: {
    
  },
  computed: {
    
  },
  methods: {
    
  },
  created () {
    
  },
  mounted () {
    this.$el.innerHTML = this.$md(md)
    
    const s = myNew(Test, 2)
    console.log(s)
    s.do()
  },
}

const myNew = (fn, ...args) => {
  if (typeof fn !== 'function') {
    throw Error('first parameter must be function')
    return
  }
  
  // 创建一个实例对象，obj.__proto__ = fn.prototype，实例共享构造函数原型链上的方法
  const obj = Object.create(fn.prototype)
  // 通过apply绑定this获取运行后的结果
  let result = fn.apply(obj, args)
  
  if (result instanceof Object && result !== null) {
    // 除非结果为引用数据类型，并且不为null，返回结果
    return result
  }
  // 否则返回新创建的对象
  return obj
}

class Test {
  constructor (res) {
    this.a = res
  }
  
  do () {
    console.log(this, this.a)
  }
}
  
</script>

<style>
</style>
